package logic

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"time"
	"zgyzk3/model/redis"
	"zgyzk3/pkg"

	"zgyzk3/zgyzk3rpc/internal/svc"
	"zgyzk3/zgyzk3rpc/zgyzk3rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *zgyzk3rpc.SendSmsRequest) (*zgyzk3rpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line

	Code := rand.Intn(9000) + 1000
	sms, err := pkg.Sendsms(in.Tel, strconv.Itoa(Code))

	if err != nil {
		return nil, fmt.Errorf("报错")
	}

	if *sms.Body.Code != "OK" {
		return nil, fmt.Errorf(*sms.Body.Message)
	}

	redis.Client.Set("sendsms"+in.Tel+in.Source, Code, time.Minute*5)

	return &zgyzk3rpc.SendSmsResponse{}, nil
}
